/**
 * Copyright (c) 2005-2012 springside.org.cn
 */
package com.kingbook.common.security;

import com.kingbook.common.exception.Exceptions;
import com.kingbook.common.utils.StringUtils;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringEscapeUtils;

import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;


/**
 * 封装各种格式的编码解码工具类.
 * 支持编码格式： 1.Hex,Base64
 * 2.xml/html
 * 3.URL
 *
 * @version 2013-01-15
 */
public class EncoderManager {

    private static final String DEFAULT_URL_ENCODING = "UTF-8";
        private static final String BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
//    private static final String BASE62 = "ef67HINO0EFGop1JKLM2cdPQRS34abTUVYghzWjklmn8iy5Z9ABvwxCDqrstuX";


    /**
     * 16进制编码.Hex
     *
     * @param input
     * @return
     */
    public static String encodeHex(byte[] input) {
        return Hex.encodeHexString(input);
    }

    /**
     * 16进制解码.Hex.
     *
     * @param input
     * @return
     */
    public static byte[] decodeHex(String input) {
        try {
            return Hex.decodeHex(input.toCharArray());
        } catch (DecoderException e) {
            throw Exceptions.unchecked(e);
        }
    }

    /**
     * Base62编码。
     */

    public static String encodeBase62(String data) {
        return encodeBase62(data, BASE62);
    }

    public static String decodeBase62(String data) {
        return decodeBase62(data, BASE62);
    }

    public static String encodeBase62(String text, String encodes) {
        byte[] data = text.getBytes();
        char[] en = encodes.toCharArray();
        StringBuffer sb = new StringBuffer(data.length * 2);
        int pos = 0, val = 0;
        for (int i = 0; i < data.length; i++) {
            val = (val << 8) | (data[i] & 0xFF);
            pos += 8;
            while (pos > 5) {
                char c = en[val >> (pos -= 6)];
                sb.append(c == 'i' ? 'a' : c == '+' ? 'b' : c == '/' ? 'c' : c);
                val &= ((1 << pos) - 1);
            }
        }
        if (pos > 0) {
            char c = en[val << (6 - pos)];
            sb.append(c == 'i' ? 'a' : c == '+' ? 'b' : c == '/' ? 'c' : c);
        }
        return sb.toString();
    }

    public static String decodeBase62(String text,  String encodes) {
        char[] data = text.toCharArray();
        char[] en = encodes.toCharArray();
        byte[] decodesBASE62 = new byte[256];
        for (int i = 0; i < en.length; i++) {
            decodesBASE62[en[i]] = (byte) i;
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream(data.length);
        int pos = 0, val = 0;
        for (int i = 0; i < data.length; i++) {
            char c = data[i];
            if (c == 'i') {
                c = data[++i];
                c = c == 'a' ? 'i' : c == 'b' ? '+' : c == 'c' ? '/' : data[--i];
            }
            val = (val << 6) | decodesBASE62[c];
            pos += 6;
            while (pos > 7) {
                baos.write(val >> (pos -= 8));
                val &= ((1 << pos) - 1);
            }
        }
        return StringUtils.toString(baos.toByteArray());
    }

    /**
     * Base64编码.
     *
     * @param input
     * @return
     */
    public static String encodeBase64String(byte[] input) {
        return Base64.encodeBase64String(input);
    }

    /**
     * Base64编码.
     *
     * @param input
     * @return
     */
    public static byte[] encodeBase64(byte[] input) {
        return Base64.encodeBase64(input);
    }

    /**
     * Base64编码.
     *
     * @param input
     * @return
     */
    public static String encodeBase64String(String input) {
        return Base64.encodeBase64String(StringUtils.getBytes(input));
    }

    /**
     * Base64编码, URL安全(将Base64中的URL非法字符'+'和'/'转为'-'和'_', 见RFC3548).
     *
     * @param input
     * @return
     */
    public static String encodeUrlSafeBase64(byte[] input) {
        return Base64.encodeBase64URLSafeString(input);
    }

    /**
     * Base64解码.
     *
     * @param input
     * @return
     */
    public static byte[] decodeBase64(byte[] input) {
        return Base64.decodeBase64(input);
    }

    /**
     * Base64解码.
     *
     * @param input
     * @return
     */
    public static String decodeBase64String(String input) {
        return StringUtils.toString(Base64.decodeBase64(StringUtils.getBytes(input)));
    }

    /**
     * Html 转码.
     *
     * @param html
     * @return
     */
    public static String escapeHtml(String html) {
        return StringEscapeUtils.escapeHtml4(html);
    }

    /**
     * Html 解码.
     *
     * @param htmlEscaped
     * @return
     */
    public static String unescapeHtml(String htmlEscaped) {
        return StringEscapeUtils.unescapeHtml4(htmlEscaped);
    }

    /**
     * Xml 转码.
     *
     * @param xml
     * @return
     */
    public static String escapeXml(String xml) {
        return StringEscapeUtils.escapeXml10(xml);
    }

    /**
     * Xml 解码.
     *
     * @param xmlEscaped
     * @return
     */
    public static String unescapeXml(String xmlEscaped) {
        return StringEscapeUtils.unescapeXml(xmlEscaped);
    }

    /**
     * URL 编码, Encode默认为UTF-8.
     *
     * @param part
     * @return
     */
    public static String urlEncode(String part) {
        try {
            return URLEncoder.encode(part, DEFAULT_URL_ENCODING);
        } catch (UnsupportedEncodingException e) {
            throw Exceptions.unchecked(e);
        }
    }

    /**
     * URL 解码, Encode默认为UTF-8.
     *
     * @param part
     * @return
     */
    public static String urlDecode(String part) {
        try {
            return URLDecoder.decode(part, DEFAULT_URL_ENCODING);
        } catch (UnsupportedEncodingException e) {
            throw Exceptions.unchecked(e);
        }
    }
}
